# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 19:37:20 2024

@author: xiaok
"""
# from mne.io import concatenate_raws, read_raw_edf
import mne
import json
#%%

filePathRoot = 'D:\\m_proj_24\\mii_app\\data\\'
# name = '07251837'
# name = '07261837'
# name = '07261845'

# name = '07261954'
name = '08022102'


filePathName = filePathRoot+name+"\\"+name+"_.edf"

raw = mne.io.read_raw_edf(filePathName,preload=True) # preload should be True, if you want to use filter like below 
nchannels, nsamples = raw.get_data().shape      

print(raw.ch_names)

# High Pass Filtering 4-40 Hz
raw.filter(l_freq=1, h_freq=90, method='iir')

# Notch filter for Removal of Line Voltage
raw.notch_filter(freqs=50)

print('fs : '+str(raw.info['sfreq']))

raw.plot(duration=5,n_channels=30,show=True)

raw.plot_psd(fmin=1,fmax=100)


#%%
with open('D:\\m_proj_24\\mii_app\\task\\task_markers.json', 'r') as file:
    markers = json.load(file)
    
label_cue_left_int = markers['Cue_onset_left'][0]
label_cue_right_int = markers['Cue_onset_right'][0]
label_cue_up_int = markers['Cue_onset_up'][0]
label_cue_down_int = markers['Cue_onset_down'][0]    

events_from_annot,event_dict = mne.events_from_annotations(raw)
# List of the events
# "trial_end":[13],             1
# "Cue_onset_left":[22],        2
# "Cue_onset_right":[23],       3
# "Cue_onset_up":[24],          4
# "Cue_onset_down":[25],        5
# "begin":[99],                 6

# fig = mne.viz.plot_events(events_from_annot,event_id=event_dict,sfreq=raw.info['sfreq'],first_samp=raw.first_samp)

event_dict_new = {value:int(float(key)) for key,value in event_dict.items()}
events_from_annot_new = events_from_annot.copy()
for i, c in enumerate(events_from_annot[:,2]):
    events_from_annot_new[i,2]=event_dict_new[c]

evnet_dict_marker = {
    'left':label_cue_left_int,
    'right':label_cue_right_int,
    'up':label_cue_up_int,
    'down':label_cue_down_int
}

signal_win_start = 0.5 #second
signal_win_end = 2.5 #second

epochs = mne.Epochs(
    raw,
    events_from_annot_new,
    event_id=evnet_dict_marker,
    tmin=signal_win_start,
    tmax=signal_win_end,
    baseline = None
)

data = epochs.get_data()
labels = epochs.events[:,-1]

# fig = mne.viz.plot_events(events_from_annot_new,event_id=event_dict_new,sfreq=raw.info['sfreq'],first_samp=raw.first_samp)







    